package org.point.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.point.common.controller.BaseController;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class SecurityInterceptor extends BaseController implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
	
        // session管理和登陆判断  
        Boolean isLogin = false;
        Object users = getSession().getAttribute("users"); 
        if (users != null) {  
            isLogin = true;  
        }
        if (!isLogin) {  
            String requestType = request.getHeader("x-requested-with");  
            boolean isAjax = false;  
            if ("XMLHttpRequest".equals(requestType)) {  
                isAjax = true;  
            }  
            // 判断是否是ajax请求 
            if (isAjax) {
                PrintWriter out = response.getWriter();
                out.print("{\"resultMsg\":\"-2\",\"msg\":\"用户尚未登陆\"}");  
                out.flush();  
                out.close();  
            } else {
                response.sendRedirect("login.do");
            }  
            return false;  
        }  
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
